﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeProjectsModel;
using System.Web.Security;
using WeProjects.Filters;
using System.IO;
using WeProjects.Models;
using WeProjects.Helps;

namespace WeProjects.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class ProjectController : Controller
    {
        private ProjectsDBEntities db = new ProjectsDBEntities();
        //
        // GET: /Project/
        public ActionResult Index()
        {            
            int usrId=int.Parse(Membership.GetUser().ProviderUserKey.ToString());
            Member m=db.Members.Find(usrId);
            var projects = db.Projects.Include(p => p.Owner).Include(p => p.ParentProject);
            if (Roles.IsUserInRole("sysadmin"))
            {
                
            }
            else
            {
                projects = db.Projects.Include(p => p.Owner).Include(p => p.ParentProject).Where(p => p.Members.Any(u => u.ID == usrId));
                projects = (from p in db.Projects
                           join p1 in projects on p.ID equals p1.ParentID
                            select p).Union(projects);
            }
            projects = projects.OrderByDescending(p => p.CreationDate);    
            IEnumerable<ProjectViewModel> model = projects.ToList().Select(p => p.ToProjectViewMode()).ToList();

            //foreach(var p in model)
            //{
            //    //List<Task> tasks = p.Tasks.ToList();
            //    var tasks = p.Tasks.Union<Task>(from t in db.Tasks
            //                                    where t.ProjectID == p.ParentID
            //                                    select t).ToList();
            //    p.Tasks = tasks;
            //    p.Tasks.OrderBy(t => t.Due);
            //}
            return View(model); 
        }


       

        //新增成员，默认存在组长ownID
        [HttpPost]
        public ActionResult NewMember(int id,string memberName)
        {
            var project = db.Projects.Find(id);
            var member = from m in db.Members
                         where m.Name == memberName
                         select m;
            if ((project != null) && (member.Count() > 0))
            {
               int memberId = db.Members.SingleOrDefault(m => m.Name == memberName).ID;  
                //添加当前项目
                db.Database.ExecuteSqlCommand("insert into ProjectMembers(ProjectID,MemberID)values('" + id + "','" + memberId + "')");
                //添加主项目
                int? parentID = project.ParentID;
                if (parentID != null)
                {
                    db.Database.ExecuteSqlCommand("if not exists(select 1 from ProjectMembers where ProjectID='" + parentID + "' and MemberID='" + memberId + "') insert into ProjectMembers(ProjectID,MemberID)values('" + parentID + "','" + memberId + "')");
                }
            }
            else
            {
                ViewBag.memberErr = "请输入正确的用户账号！";
            }
            return RedirectToAction("Members","Member",new {id=id});
        }
        //删除成员
        public ActionResult MemberDel(int memberId,int projectId)
        {
            var project=db.Projects.Find(projectId);
            if ((project != null) && (db.Members.Find(memberId) != null))
            {
                //删除当前项目的成员  deal with this later.
                db.Database.ExecuteSqlCommand("delete from ProjectMembers where ProjectID='" + projectId + "' and MemberID='" + memberId + "'");
                //删除主项目，如果不存在其他子项目  deal with this later.
                int? parentID = project.ParentID;
                db.Database.ExecuteSqlCommand("if not exists(select 1 from ProjectMembers where MemberID='" + memberId + "' and projectid in (select id from projects where parentid='" + parentID + "')) delete from ProjectMembers where projectid='" + parentID + "' and memberid='" + memberId + "'");

                if(project.OwnerID==memberId)
                {
                    project.OwnerID = null;
                    db.Entry(project).State = EntityState.Modified;
                    db.SaveChanges();
                }
            }
            else
            {
                return HttpNotFound();
            }
            return RedirectToAction("Members", "Member", new { id = projectId });
        }
        /// <summary>
        /// 文件，显示当前项目组文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Files(int id)
        {
            var project = db.Projects.Find(id);
            if(project==null)
            {
                return HttpNotFound();
            }
            ViewBag.projectTitle = project.Title;
            ViewBag.projectOwnId = project.OwnerID;
            var files = from f in db.Documents
                        where f.ProjectID == id
                        select f;
            return View(files);
        }
        /// <summary>
        /// 上传附件，上传至Files/Project/projectID
        /// </summary>
        /// <param name="uploadFile"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Upload(HttpPostedFileBase uploadFile, int? id)
        {
            //try
            //{
            if (uploadFile != null && uploadFile.ContentLength > 0)
            {
                string path = Server.MapPath("~/Files/project/"+id+"/");
                string fileName = Path.GetFileName(uploadFile.FileName);
                int fileSize = uploadFile.ContentLength / 1024;//文件大小KB
                string newpath = Path.Combine(path, fileName);
                //string newurl = "/Files/" + id.ToString() + "/" + fileName;
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                uploadFile.SaveAs(newpath);
                var doc = new Document();
                doc.Name = fileName;
                doc.Size = fileSize;
                doc.UploadDateTime = DateTime.Now;
                doc.ProjectID = id;//项目id
                doc.UploaderID = int.Parse(Membership.GetUser().ProviderUserKey.ToString());     
                db.Documents.Add(doc);
                db.SaveChanges();
            }
            return RedirectToAction("Files", new { id = id });
            //}
            //catch (Exception e)
            //{
            //    return RedirectToAction("/Index/");
            //}
        }
        /// <summary>
        ///下载文件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult DownloadFile(int file,int project)
        {
            Document document = db.Documents.Find(file);
            if (document == null)
            {
                return HttpNotFound();
            }
            string fileName = document.Name;
            string path = Server.MapPath("~/Files/project/"+project+"/" + fileName);

            string downName = Path.GetFileName(path);
            return File(path, "1", downName);
        }

        public ActionResult DeleteFile(int file,int project)
        {
            Document document = db.Documents.Find(file);
            //获取文件名
            string fileName = document.Name;
            string path = Server.MapPath("~/Files/project/"+project+"/");
            string newpath = Path.Combine(path, fileName);
            //如果存在则删除
            if (System.IO.File.Exists(newpath))
            {
                System.IO.File.Delete(newpath);
            }
            db.Documents.Remove(document);
            db.SaveChanges();
            return RedirectToAction("Files", new { id = project});
        }

        //
        // GET: /Project/Details/5
        //The tasks.
        public ActionResult Details(int id = 0)
        {
            IEnumerable<Task> tasks;// = null;
            Project project = db.Projects.Find(id);
            if (project == null)
            {
                return HttpNotFound();
            }
            tasks = from t in project.Tasks
                        select t;
            if(project.ParentID!=null)            
            {
                tasks = tasks.Union<Task>(from t in db.Tasks
                                    where t.ProjectID == project.ParentID
                                    select t);                
            }
            //主项目的任务列表
            tasks = tasks.OrderBy(t => t.Due);
            ViewBag.mainTask = tasks.ToList();// db.Tasks.ToList();
            ViewBag.ProjectID = id;

            if(project.Members!=null&&project.Members.Where(m=>m.Name==User.Identity.Name).Count()>0)
            {
                ViewBag.TaskDocumentsVisible = true;
            }
            else
            {
                ViewBag.TaskDocumentsVisible = false;
            }

            return View(project);
        }

        //
        // GET: /Project/Create

        public ActionResult Create(int parentID=0)
        {
            //ViewBag.memberErr = "请输入用户账号";
            if (parentID != 0)
            {
                Project pj = db.Projects.Find(parentID);
                if (pj == null)
                {
                    return HttpNotFound();
                }
                //ViewBag.projectTitle = pj.Title+" > ";
                //ViewBag.isBigItem = id;
            }
            ViewBag.ParentProjectID = parentID == 0 ? 0 : parentID;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(ProjectViewModel model,int parentProjectID)//int? id, string title, string serNum, string desc, int owner, string memberName)
        {
            if (ModelState.IsValid)
            {      
                if(parentProjectID!=null&&parentProjectID!=0)
                {
                    model.ParentID = parentProjectID;
                }
                var project=db.Projects.Add(model.ToProjectDataModel());
                db.SaveChanges();
                return RedirectToAction("Details", new { id = project.ParentID==null?project.ID:parentProjectID });
            }
            return View();            
        }

        //
        // GET: /Project/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Project project = db.Projects.Find(id);
            if (project == null)
            {
                return HttpNotFound();
            }
            //ViewBag.projectOwner = db.Members.SingleOrDefault(m => m.ID == project.OwnerID).Name;
            return View(project.ToProjectViewMode());
        }

        //
        // POST: /Project/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(ProjectViewModel model)// int id,string title,string serNum,string desc,int owner,string memberName)
        {
            if (ModelState.IsValid)
            {
                var project = db.Projects.Find(model.ID);// model.ToProjectDataModel();
                //model.ParentID = project.ParentID;
                //model.OwnerID = project.OwnerID;
                //model.CreationDate = project.CreationDate;
                project.Title = model.Title;
                project.Description = model.Descritpion;
                project.SerialNumber = model.SerialNumber;
                project.SubProjectsFileUploadAllowed = model.SubProjectsFileUploadAllowed;
                project.TaskDueTimeEnforcement = model.TaskDueTimeEnforcement;

                db.Entry(project).State = EntityState.Modified;
                db.SaveChanges();

                return RedirectToAction("Index");
            }
            //var project = db.Projects.Find(id);
            //project.ID = id;
            //project.Title = title;
            //project.SerialNumber = serNum;
            //project.Description = desc;
            //project.OwnerID = owner;

            //int memberId;
            //var member = from m in db.Members
            //             where m.Name == memberName
            //             select m;
            //if (member.Count() > 0)
            //{
            //    memberId = db.Members.SingleOrDefault(m => m.Name == memberName).ID;
            //    project.OwnerID = memberId;
            //}
            //else
            //{
            //    ViewBag.memberErr = "输入的账号不存在，请重新输入！";
            //    return View();
            //}

            //if (ModelState.IsValid)
            //{
            //    db.Entry(project).State = EntityState.Modified;                
            //    db.SaveChanges();
            //    if (member != null)
            //    {
            //        //变更管理员
            //        db.Database.ExecuteSqlCommand("if not exists(select 1 from ProjectMembers where ProjectID='"+id+"' and MemberID='"+memberId+"') insert into ProjectMembers(ProjectID,MemberID)values('" + id + "','" + memberId + "')");
            //        //添加主项目
            //        if (project.ParentID != null)
            //        {
            //            db.Database.ExecuteSqlCommand("if not exists(select 1 from ProjectMembers where ProjectID='" + project.ParentID + "' and MemberID='" + memberId + "') insert into ProjectMembers(ProjectID,MemberID)values('" + project.ParentID + "','" + memberId + "')");
            //        }
            //    }
            //    return RedirectToAction("Index");
            //}
            return View(model);
        }

        //
        // GET: /Project/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Project project = db.Projects.Find(id);
            if (project == null)
            {
                return HttpNotFound();
            }
            return View(project.ToProjectViewMode());
        }

        //
        // POST: /Project/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Project project = db.Projects.Find(id);
            Utility.RemoveBelongs<Document>(project.Documents, db);
            db.Projects.Remove(project);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        [HttpPost]
        public ActionResult SetOwner(int projectID,string ownerName)
        {
            var project = db.Projects.Find(projectID);
            if (project != null)//Project exists.
            {
                var user = Membership.GetUser(ownerName);
                if(user!=null)//User exists.
                {
                    if(project.Members.Where(m=>m.Name.ToLower()==ownerName.ToLower()).Count()>=1)//User is already a member of project.
                    {
                        project.OwnerID = db.Members.Where(m => m.Name.ToLower() == ownerName.ToLower()).FirstOrDefault().ID;
                        db.Entry(project).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
            }
            return RedirectToAction("Members", "Member", new { id = projectID });
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}